package model

import (
    "errors"
    "gorm.io/gorm"
    "time"
    "yi-shou-backstage/util"
)

// 用户表
type User struct {
    ID int `gorm:"primaryKey;comment:编号" json:"id"`
    CreateAt time.Time `gorm:"comment:创建时间" json:"create_at,omitempty" validate:"omitempty" label:"创建时间"`
    UpdateAt time.Time `gorm:"comment:创建时间" json:"update_at,omitempty" validate:"omitempty" label:"更新时间"`
    DeletedAt gorm.DeletedAt `gorm:"index;comment:删除时间" json:"deleted_at,omitempty" validate:"omitempty" label:"删除时间"`
    Name string `gorm:"type:varchar(20);unique;not null;comment:用户名" json:"name,omitempty" validate:"omitempty" label:"用户名"`
    PassWord string `gorm:"type:varchar(20);not null;comment:密码" json:"password,omitempty" validate:"omitempty" label:"密码"`
    Mobile string `gorm:"type:varchar(11);unique;not null;comment:手机号" json:"mobile,omitempty" validate:"omitempty" label:"手机号"`
    Code string `gorm:"type:varchar(6);comment:验证码" json:"code,omitempty" validate:"omitempty" label:"验证码"`
    NickName string `gorm:"type:varchar(50);unique;comment:昵称" json:"nick_name,omitempty" validate:"omitempty" label:"昵称"`
    Photo string `gorm:"type:varchar(256);comment:头像" json:"photo,omitempty" validate:"omitempty" label:"头像"`
    Intro string `gorm:"type:varchar(1024);comment:头条号简介" json:"intro,omitempty" validate:"omitempty" label:"头条号简介"`
    Email string `gorm:"type:varchar(32);comment:邮箱" json:"email,omitempty" validate:"email,omitempty" label:"邮箱"`

    // 用户 Token 令牌
    Token string `gorm:"-" json:"token"`
    // 用于刷新 token 的令牌
    RefreshToken string `gorm:"-" json:"refresh_token"`  // 通过 struct 读写会忽略该字段

    // 添加自关联
    Followers []*User `gorm:"many2many:user_followers"`
    //Followers []*Follower `gorm:"many2many:user_followers"`
}

// 粉丝表
//type Follower struct {
//  ID uint `gorm:"primaryKey" json:"id"`
//  Name string `gorm:"type:varchar(20);not null;comment:用户名" json:"name,omitempty"`
//  Photo string `gorm:"type:varchar(256);comment:头像" json:"photo,omitempty"`
//  添加反向关联
  //Users []*User `gorm:"many2many:user_followers"`
//}

// 用户关联模型（不用做建表，仅用于代码中序列化数据）
type UserFollowers struct {
    UserID uint `json:"user_id"`
    FollowerID uint `json:"follower_id"`
}

func NewUser() *User {
    return &User{}
}

// 通过主键查询
func GetUser(user_id int) *User {
    var user User
    err := db.First(&user, user_id).Error
    if errors.Is(err, gorm.ErrRecordNotFound) {
        util.LogEntry.Errorf("User is not exist, user_id = %d \n", user_id)
        return nil
    }
    return &user
}

// 条件查询，返回一个查询对象
func QueryUserFirst(Conditions User) *User {
    var user User
    var err error
    if Conditions.Mobile != "" {
        err = db.Where("mobile = ?", Conditions.Mobile).First(&user).Error
    }
    if err != nil {
        util.LogEntry.Errorf("Query User error: %s \n", err)
        return nil
    }
    return &user
}

// 条件查询，返回一个查询结果集
func QueryUser() {

}

// 新增用户
func CreateUser(user *User) *User {
    err := db.Create(&user).Error
    if err != nil {
        util.LogEntry.Errorf("Create User error: %s \n", err)
        return nil
    }
    return user
}

// 更新用户
func UpdateUser(user_id int, obj *User) *User {
    var user User
    user.ID = user_id
    err := db.Model(&user).Updates(obj).Error
    if err != nil {
        util.LogEntry.Errorf("Update User error: %s \n", err)
        return nil
    }
    return &user
}

// 查询粉丝
func GetFollowers(user_id int, page int, per_page int) (int64, []User) {
    var Followers []User
    var total int64
    offset := -1
    limit := -1
    if page == 1 {
        limit = per_page
    } else if page > 1 {
        offset = (page - 1) * per_page
        limit = per_page
    }
    // 校验user_id
    user := GetUser(user_id)
    if user == nil {
        util.LogEntry.Errorf("用户不存在, user_id = %s \n", user_id)
        return total, Followers
    }

    // 根据 user_id 在关联表 user_followers 查询对应的 follower_id 集合 follower_ids
    //query_followers_sql := "SELECT follower_id FROM user_followers WHERE user_id = ?"
    //rows, err := db.Exec("select follower_id from user_followers where user_id = 1").Rows()

    var user_followers []UserFollowers
    err := db.Where("user_id = ?", user_id).Find(&user_followers).Error
    if err != nil {
        util.LogEntry.Errorf("Query user_followers error, error: %s \n", err)
    }
    var follower_ids []uint
    for _, val := range user_followers{
        follower_ids = append(follower_ids, val.FollowerID)
    }

    // 根据 follower_ids 查询 User 表，查询真正的粉丝信息
    err = db.Where("ID in ?", follower_ids).Find(&Followers).Count(&total).Error
    err = db.Where("ID in ?", follower_ids).Offset(offset).Limit(limit).Find(&Followers).Error
    if err != nil {
        util.LogEntry.Errorf("Query User error, error = %s \n", err)
        return total, Followers
    }
    return total, Followers
}